package com.GamersCom.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.User;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.UserMgr;

/**
 * Servlet implementation class Profile
 */
public class Profile extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	 

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request,response);
	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		//retrieve the session
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		String nextView;
		
		if (username == null) //direct to login page if not login
		{
//			String error = "You must login first! please click <a href=\"login\"> here </a> to login! ";
//			request.setAttribute("error", error);
			nextView = "login.jsp";
		}
		else
		{
			MgrFactory factory = (MgrFactory) this.getServletContext()
					.getAttribute("mgrFactory");
			UserMgr userMgr = factory.getUserMgr();
			User user = (User) userMgr.getUserByUsername(username);
			
			String post = request.getParameter("submit");			
			// handles update operation
			if (post != null)
			{
				String firstName = request.getParameter("firstname");
				String lastName = request.getParameter("lastname");
				String securityQuestion = request.getParameter("securityquestion");
				String answer = request.getParameter("answer");
				user.setFirstName(firstName);
				user.setLastName(lastName);
				user.setSecurityQuestion(securityQuestion);
				user.setAnswer(answer);
				
				userMgr.updateUser(user);
				
				String msg = "You have successfully update your profile!";	
				request.setAttribute("msg", msg);
			}
			
			// send the value back to the view
			request.setAttribute("firstName", user.getFirstName());
			request.setAttribute("lastName", user.getLastName());
			request.setAttribute("email", user.getEmail());
			request.setAttribute("securityquestion", user.getSecurityQuestion());
			request.setAttribute("answer", user.getAnswer());
			
			nextView = "profile.jsp";
		}
		
		
		request.getRequestDispatcher(nextView).forward(request, response);
		
	}
}
